//
//  chatViewController.m
//  AIM
//
//  Created by user10 on 2017/6/20.
//  Copyright © 2017年 user10. All rights reserved.
//

#import "chatViewController.h"
#import "chatViewCell.h"
#import "NetWorkTools.h"
#import "chatModel.h"
#import <Masonry.h>
#import <UIImageView+WebCache.h>
#import "AimTapGestureRecognizer.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <GCDAsyncUdpSocket.h>
#import <GCDAsyncSocket.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
#import "SBJson4.h"
#import <ifaddrs.h>
#import <arpa/inet.h>
#import "FSCustomButton.h"
#import "UIImage+Extension.h"
#import "voiceViewController.h"
#import "LVRecordTool.h"
#import <FSAudioStream.h>
#import "DemoViewController.h"
#import "RecordAudio.h"
#import "MBProgressHUD.h"
#import "playVoiceViewController.h"
#import "chatViewImgCell.h"
#import "chatViewVideoCell.h"
#import "chatViewVoiceCell.h"
#import <MJRefresh.h>
#import "UDPManage.h"
#import "TCPManage.h"
#import "logModel.h"
#import "DataBase.h"

#define screenWidth [UIScreen mainScreen].bounds.size.width
#define BIG_IMG_WIDTH  [UIScreen mainScreen].bounds.size.width
#define BIG_IMG_HEIGHT [UIScreen mainScreen].bounds.size.width * 16 / 9


@interface chatViewController ()<UITableViewDelegate,UITableViewDataSource,GCDAsyncUdpSocketDelegate,GCDAsyncSocketDelegate,UITextFieldDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,DemoViewControllerDelegate,AVPlayerViewControllerDelegate,UDPManageDelegate,TCPManageDelegate>
@property (nonatomic,weak)UITableView *tabV;
@property (nonatomic,weak)UIImageView *imageV;
@property (nonatomic, strong) AVPlayerViewController  *avPlayer;
@property (nonatomic,weak)UIView *backView;
//顶部view
@property (nonatomic,weak)UIView *topView;
@property (nonatomic,weak)UIImageView *icon;
@property (nonatomic,weak)UILabel *time;
@property (nonatomic,weak)UILabel *category;
@property (nonatomic,weak)UILabel *from;
@property (nonatomic,weak)UILabel *categoryL;
@property (nonatomic,weak)UILabel *fromL;
@property (nonatomic,weak)UIButton *closeBtn;

//底部view
@property (nonatomic,weak)UIView *bottomView;
@property (nonatomic,weak)UIButton *addBtn;
@property (nonatomic,weak)UITextField *textField;
@property (nonatomic,weak)UIButton *sendBtn;

@property (nonatomic,strong)NSMutableArray *arr;
@property (nonatomic,strong)NSMutableArray *chatResultArr;

@property (nonatomic,assign)CGFloat cellHeight;

//隐藏底部的view
@property (nonatomic,weak) UIView *btnView;
@property (nonatomic,weak) FSCustomButton *cameraButton;
@property (nonatomic,weak) FSCustomButton *photoButton;
@property (nonatomic,weak) FSCustomButton *videoButton;
@property (nonatomic,weak) FSCustomButton *voiceButton;

// UDP socket
@property (strong, nonatomic)GCDAsyncUdpSocket * udpSocket;
// TCP socket
@property (strong, nonatomic) GCDAsyncSocket *clientSocket;
#define udpPort 9998

@property (strong, nonatomic) NSString *userID;
@property(nonatomic ,strong)NSString *dataName;
@property(nonatomic ,strong)NSString *dataString;
@property(nonatomic ,strong)NSString *textDataString;
@property(nonatomic ,strong)NSString *dataType;
@property(nonatomic ,strong)NSData *data;
@property(nonatomic ,strong)NSURL *voiceUrl;
@property (nonatomic, strong)RecordAudio *recordAudio;
@property(nonatomic ,strong)NSString *userId;
@property(nonatomic ,strong)MBProgressHUD *HUD;
@property(nonatomic ,strong)NSIndexPath *indexPathFlag;
@property(nonatomic ,strong)NSString *targetDate;

@property(nonatomic ,strong)UDPManage *UDPManage;
@property(nonatomic ,strong)TCPManage *TCPManage;

@property(nonatomic ,strong)UILongPressGestureRecognizer * longPressGesture;


@end
//指定cellIdentifier为自定义的cell
//static  NSString *CellIdentifier = @"chatViewCell" ;


@implementation chatViewController{
    UIScrollView *background;
    UIImageView *imageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置tableviewCell紧贴着tableview顶端
    self.automaticallyAdjustsScrollViewInsets = NO;
    RecordAudio *recordAudio = [[RecordAudio alloc]init];
    _recordAudio = recordAudio;
    NSUserDefaults *user  = [NSUserDefaults standardUserDefaults];
    _userID = [user objectForKey:@"TANTO_CD"];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self setupView];
    [self loadData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UDPReconnection) name:@"UDPReconnection" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UDPClose) name:@"UDPClose" object:nil];
    //udp登录socket
    UDPManage *manager = [UDPManage shareUDPManage];
    _UDPManage = manager;
    _UDPManage.delegate = self;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:COMPANY forKey:@"COMPANY"];
    [dict setObject:_messageID forKey:@"MESSAGEID"];
    [dict setObject:_userID forKey:@"USERID"];
    NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
    
    NSString *strResult = [NSString stringWithFormat:@"LOGIN@@%@",str
                           ];
    NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
    
    [_UDPManage startScanWith:data];
    
    TCPManage *tcpmanager = [TCPManage shareTCPManage];
    _TCPManage = tcpmanager;
    _TCPManage.delegate = self;
    
}

- (void)setupView{
    UIView *backView = [[UIView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:backView];
    _backView = backView;
    
    UITableView *tabV = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tabV.delegate = self;
    tabV.dataSource = self;
    tabV.rowHeight = UITableViewAutomaticDimension;
    tabV.estimatedRowHeight = 100;
    tabV.separatorStyle = NO;
    
    
    [self.backView addSubview:tabV];
    _tabV = tabV;
    [self registerCell];
    [_tabV reloadData];
    _tabV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 下拉刷新的网络请求的处理
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self loadOldData];
            
            [self.tabV.mj_header endRefreshing];
        });
    }];
    
    [self.tabV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backView.mas_top).offset(100);
        make.left.mas_equalTo(self.backView.mas_left).offset(0);
        make.right.mas_equalTo(self.backView.mas_right).offset(0);
        make.bottom.mas_equalTo(self.backView.mas_bottom).offset(-44);
    }];
    
    //顶部的view
    UIView *topView = [[UIView alloc]init];
    [self.backView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.backView.mas_top).offset(0);
        make.bottom.mas_equalTo(self.tabV.mas_top).offset(0);
        make.right.mas_equalTo(self.backView.mas_right).offset(0);
        make.left.mas_equalTo(self.backView.mas_left).offset(0);
    }];
    topView.backgroundColor = [UIColor whiteColor];
    _topView = topView;
    
    //头像
    UIImageView *iconV = [[UIImageView alloc]init];
    [self.topView addSubview:iconV];
    iconV.image = [UIImage imageNamed:@"me"];
    [iconV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.topView);
        make.left.mas_equalTo(self.topView.mas_left).offset(20);
        make.height.and.width.mas_equalTo(70);
    }];
    _icon = iconV;
    
    //时间
    UILabel *time = [[UILabel alloc]init];
    time.font = [UIFont systemFontOfSize:13];
    [self.topView addSubview:time];
    time.text = _timeStr;
    [time mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.icon.mas_top);
        make.left.mas_equalTo(self.icon.mas_right).offset(10);
        make.height.mas_equalTo(20);
        make.right.mas_equalTo(self.backView.mas_right).offset(-70);
    }];
    _time = time;
    
    //category
    UILabel *category = [[UILabel alloc]init];
    category.font = [UIFont systemFontOfSize:13];
    [self.topView addSubview:category];
    category.text = @"category:";
    [category mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.time.mas_bottom).offset(5);
        make.left.mas_equalTo(self.time.mas_left);
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(60);
    }];
    _category = category;
    
    //from
    UILabel *from = [[UILabel alloc]init];
    from.font = [UIFont systemFontOfSize:13];
    [self.topView addSubview:from];
    from.text = @"from:";
    [from mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.category.mas_bottom).offset(5);
        make.left.mas_equalTo(self.category.mas_left);
        make.height.mas_equalTo(20);
        make.width.mas_equalTo(60);
    }];
    _from = from;
    
    //category 内容
    UILabel *categoryL = [[UILabel alloc]init];
    categoryL.font = [UIFont systemFontOfSize:13];
    [self.topView addSubview:categoryL];
    categoryL.text = _categoryStr;
    [categoryL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.category.mas_top);
        make.left.mas_equalTo(self.category.mas_right).offset(1);
        make.height.mas_equalTo(20);
        make.right.mas_equalTo(self.time.mas_right);
    }];
    _categoryL = categoryL;
    
    //from 内容
    UILabel *fromL = [[UILabel alloc]init];
    fromL.font = [UIFont systemFontOfSize:13];
    [self.topView addSubview:fromL];
    fromL.text = _fromStr;
    [fromL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.from.mas_top);
        make.left.mas_equalTo(self.from.mas_right).offset(1);
        make.height.mas_equalTo(20);
        make.right.mas_equalTo(self.time.mas_right);
    }];
    _fromL = fromL;
    
    //关闭按钮
    UIButton *closeBtn = [[UIButton alloc]init];
    [self.topView addSubview:closeBtn];
    closeBtn.layer.cornerRadius = 5;
    [closeBtn addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setTitle:@"close" forState:UIControlStateNormal];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.time.mas_top);
        make.left.mas_equalTo(self.time.mas_right).offset(3);
        make.right.mas_equalTo(self.topView.mas_right).offset(-3);
        make.height.mas_equalTo(40);
    }];
    closeBtn.backgroundColor = [UIColor grayColor];
    _closeBtn = closeBtn;
    
    
    //底部view
    UIView *bottomView = [[UIView alloc]init];
    [self.backView addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.tabV.mas_bottom).offset(0);
        make.bottom.mas_equalTo(self.backView.mas_bottom).offset(0);
        make.right.mas_equalTo(self.backView.mas_right).offset(0);
        make.left.mas_equalTo(self.backView.mas_left).offset(0);
    }];
    bottomView.backgroundColor = [UIColor whiteColor];
    _bottomView = bottomView;
    
    //多媒体选择按钮
    UIButton *addBtn = [[UIButton alloc]init];
    [addBtn addTarget:self action:@selector(viewChanged) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:addBtn];
    [addBtn setImage:[UIImage imageNamed:@"chat_bottom_up_nor"] forState:UIControlStateNormal];
    [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bottomView.mas_top).offset(0);
        make.left.mas_equalTo(self.bottomView.mas_left).offset(0);
        make.width.and.height.mas_equalTo(44);
    }];
    _addBtn = addBtn;
    
    //发送按钮
    UIButton *sendBtn = [[UIButton alloc]init];
    sendBtn.layer.cornerRadius = 3;
    [self.bottomView addSubview:sendBtn];
    [sendBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [sendBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bottomView.mas_top).offset(7);
        make.right.mas_equalTo(self.bottomView.mas_right).offset(-5);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(30);
    }];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [sendBtn setTitle:@"Send" forState:UIControlStateNormal];
    sendBtn.backgroundColor = [UIColor colorWithRed:20/255.0 green:176/255.0 blue:249/255.0 alpha:1];
    _sendBtn = sendBtn;
    
    //内容输入框
    UITextField *textField = [[UITextField alloc]init];
    [textField setBackground:[UIImage imageNamed:@"chat_bottom_textfield"]];
    textField.delegate = self;
    [self.bottomView addSubview:textField];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bottomView.mas_top).offset(3);
        make.left.mas_equalTo(self.addBtn.mas_right).offset(5);
        make.right.mas_equalTo(self.sendBtn.mas_left).offset(-5);
        make.bottom.mas_equalTo(self.bottomView.mas_bottom).offset(-3);
    }];
    _textField = textField;
    
    //隐藏在底部的view
    UIView *btnView = [[UIView alloc]init];
    btnView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:btnView];
    [btnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bottomView.mas_bottom).offset(0);
        make.left.mas_equalTo(self.backView.mas_left).offset(0);
        make.right.mas_equalTo(self.backView.mas_right).offset(0);
        make.height.mas_equalTo(100);
    }];
    _btnView = btnView;
    
    //相机按钮
    FSCustomButton *cameraButton = [[FSCustomButton alloc] init];
    cameraButton.adjustsTitleTintColorAutomatically = YES;
    cameraButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [cameraButton setTitle:@"Photo" forState:UIControlStateNormal];
    [cameraButton setImage:[UIImage imageNamed:@"postcomment_menu_photo"] forState:UIControlStateNormal];
    cameraButton.buttonImagePosition = FSCustomButtonImagePositionTop;
    cameraButton.titleEdgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);
    [self.btnView addSubview:cameraButton];
    [cameraButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.btnView.mas_top).offset(0);
        make.left.mas_equalTo(self.btnView.mas_left).offset(0);
        make.bottom.mas_equalTo(self.btnView.mas_bottom).offset(0);
        make.width.mas_equalTo(BIG_IMG_WIDTH * 1/4);
    }];
    [cameraButton addTarget:self action:@selector(photoClick) forControlEvents:UIControlEventTouchUpInside];
    _cameraButton = cameraButton;
    
    //照片按钮
    FSCustomButton *photoButton = [[FSCustomButton alloc] init];
    photoButton.adjustsTitleTintColorAutomatically = YES;
    photoButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [photoButton setTitle:@"Camera" forState:UIControlStateNormal];
    [photoButton setImage:[UIImage imageNamed:@"postcomment_menu_camera"] forState:UIControlStateNormal];
    photoButton.buttonImagePosition = FSCustomButtonImagePositionTop;
    photoButton.titleEdgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);
    photoButton.userInteractionEnabled = YES;
    [self.btnView addSubview:photoButton];
    [photoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.btnView.mas_top).offset(0);
        make.left.mas_equalTo(self.cameraButton.mas_right).offset(0);
        make.bottom.mas_equalTo(self.btnView.mas_bottom).offset(0);
        make.width.mas_equalTo(BIG_IMG_WIDTH * 1/4);
    }];
    [photoButton addTarget:self action:@selector(clickCamera) forControlEvents:UIControlEventTouchUpInside];
    _photoButton = photoButton;
    
    //视频按钮
    FSCustomButton *videoButton = [[FSCustomButton alloc] init];
    videoButton.adjustsTitleTintColorAutomatically = YES;
    videoButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [videoButton setTitle:@"Video" forState:UIControlStateNormal];
    [videoButton setImage:[UIImage imageNamed:@"postcomment_menu_video"] forState:UIControlStateNormal];
    videoButton.buttonImagePosition = FSCustomButtonImagePositionTop;
    videoButton.titleEdgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);
    [self.btnView addSubview:videoButton];
    [videoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.btnView.mas_top).offset(0);
        make.left.mas_equalTo(self.photoButton.mas_right).offset(0);
        make.bottom.mas_equalTo(self.btnView.mas_bottom).offset(0);
        make.width.mas_equalTo(BIG_IMG_WIDTH * 1/4);
    }];
    [videoButton addTarget:self action:@selector(clickVideo) forControlEvents:UIControlEventTouchUpInside];
    _videoButton = videoButton;
    
    
    //语音按钮
    FSCustomButton *voiceButton = [[FSCustomButton alloc] init];
    voiceButton.adjustsTitleTintColorAutomatically = YES;
    voiceButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [voiceButton setTitle:@"Voice" forState:UIControlStateNormal];
    [voiceButton setImage:[UIImage imageNamed:@"postcomment_menu_voice"] forState:UIControlStateNormal];
    voiceButton.buttonImagePosition = FSCustomButtonImagePositionTop;
    voiceButton.titleEdgeInsets = UIEdgeInsetsMake(10, 0, 0, 0);
    [self.btnView addSubview:voiceButton];
    [voiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.btnView.mas_top).offset(0);
        make.left.mas_equalTo(self.videoButton.mas_right).offset(0);
        make.bottom.mas_equalTo(self.btnView.mas_bottom).offset(0);
        make.width.mas_equalTo(BIG_IMG_WIDTH * 1/4);
    }];
    [voiceButton addTarget:self action:@selector(clickVoice) forControlEvents:UIControlEventTouchUpInside];
    _voiceButton = voiceButton;
    
    //监听键盘的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(viewChanged:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    self.tabV.delegate = self;
    self.tabV.dataSource = self;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UDPReconnection" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UDPClose" object:nil];
}

- (void)UDPClose{
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:COMPANY forKey:@"COMPANY"];
    [dict setObject:_messageID forKey:@"MESSAGEID"];
    [dict setObject:_userID forKey:@"USERID"];
    NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
    
    NSString *strResult = [NSString stringWithFormat:@"UNLOGIN@@%@",str
                           ];
    NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
    
    [_UDPManage startScanWith:data];
//    [_UDPManage disconnect];
    
}

- (void)UDPReconnection{
    UDPManage *manager = [UDPManage shareUDPManage];
    _UDPManage = manager;
    _UDPManage.delegate = self;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:COMPANY forKey:@"COMPANY"];
    [dict setObject:_messageID forKey:@"MESSAGEID"];
    [dict setObject:_userID forKey:@"USERID"];
    NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
    
    NSString *strResult = [NSString stringWithFormat:@"LOGIN@@%@",str
                           ];
    NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
    
    [_UDPManage startScanWith:data];
    
    TCPManage *tcpmanager = [TCPManage shareTCPManage];
    _TCPManage = tcpmanager;
    _TCPManage.delegate = self;
}

- (void)registerCell
{
    [_tabV registerClass:[chatViewCell class] forCellReuseIdentifier:NSStringFromClass([chatViewCell class])];
    [_tabV registerClass:[chatViewImgCell class] forCellReuseIdentifier:NSStringFromClass([chatViewImgCell class])];
    [_tabV registerClass:[chatViewVideoCell class] forCellReuseIdentifier:NSStringFromClass([chatViewVideoCell class])];
    [_tabV registerClass:[chatViewVoiceCell class] forCellReuseIdentifier:NSStringFromClass([chatViewVoiceCell class])];
}

- (void)loadData{
    //网络请求
    NSString *webServiceStr = [NSString stringWithFormat:
                               @"<web:getPostCommentData>\
                               <arg0>%@</arg0>\
                               <arg1>%@</arg1>\
                               <arg2>50</arg2>\
                               <arg3></arg3>\
                               </web:getPostCommentData>",COMPANY,_messageID];
    //初始化网络工具类
    NetWorkTools *tools = [NetWorkTools shareTools];
    //发送网络请求
    
    [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostCommentImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *string = result;
        //截取返回失败的结果字符串
        NSRange returnRange = [string rangeOfString:@"<return>"];
        NSRange returnendRange = [string rangeOfString:@"</return>"];
        NSRange rangeEnd = NSMakeRange(returnRange.location + returnRange.length, returnendRange.location - returnRange.location - returnRange.length);
        if (rangeEnd.location != NSNotFound) {
            NSString *successResultStr = [string substringWithRange:rangeEnd];
            //判断是否返回了错误的字符串
            if (![successResultStr isEqualToString:@"FAILED"]) {
                NSRange startRange = [string rangeOfString:@"@@"];
                NSRange endRange = [string rangeOfString:@"</return>"];
                NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
                if (range.location != NSNotFound) {
                    NSString *resultString = [string substringWithRange:range];
                    NSData * getJsonData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
                    NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
                    NSMutableArray *arr = [NSMutableArray array];
                    [arr addObjectsFromArray:[getDict objectForKey:@"DATA"]];
                    _targetDate = [getDict objectForKey:@"MSG_NEW_TARGET_DATE"];
                    NSArray* reversedArray = [[arr reverseObjectEnumerator] allObjects];
                    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:reversedArray];
                    _arr = tempArr;
                    NSMutableArray *mgroupsArray = [NSMutableArray array];
                    for (NSDictionary *chatDict in _arr) {
                        chatModel *chatResult = [chatModel chatWithDictionary:chatDict];
                        [mgroupsArray addObject:chatResult];
                    }
                    _chatResultArr = mgroupsArray;
                    
                    [self.tabV reloadData];
                    
                    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:_chatResultArr.count - 1 inSection:0];
                    [self.tabV scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                }else{
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Network error" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                    alert.delegate = self;
                    [alert show];
                }
                
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Network error" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
        
    }];
    
    [self.tabV reloadData];
}

- (void)loadOldData{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            NSLog(@"有网");
            NSString *webServiceStr = [NSString stringWithFormat:
                                       @"<web:getPostCommentData>\
                                       <arg0>%@</arg0>\
                                       <arg1>%@</arg1>\
                                       <arg2>50</arg2>\
                                       <arg3>%@</arg3>\
                                       </web:getPostCommentData>",COMPANY,_messageID,_targetDate];
            //初始化网络工具类
            NetWorkTools *tools = [NetWorkTools shareTools];
            //发送网络请求
            
            [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostCommentImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
                NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSString *string = result;
                //截取返回失败的结果字符串
                NSRange returnRange = [string rangeOfString:@"<return>"];
                NSRange returnendRange = [string rangeOfString:@"</return>"];
                NSRange rangeEnd = NSMakeRange(returnRange.location + returnRange.length, returnendRange.location - returnRange.location - returnRange.length);
                if (rangeEnd.location != NSNotFound) {
                    NSString *successResultStr = [string substringWithRange:rangeEnd];
                    //判断是否返回了错误的字符串
                    if (![successResultStr isEqualToString:@"FAILED"]) {
                        NSRange startRange = [string rangeOfString:@"@@"];
                        NSRange endRange = [string rangeOfString:@"</return>"];
                        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
                        if (range.location != NSNotFound) {
                            NSString *resultString = [string substringWithRange:range];
                            NSData * getJsonData = [resultString dataUsingEncoding:NSUTF8StringEncoding];
                            NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
                            NSMutableArray *arr = [NSMutableArray array];
                            [arr addObjectsFromArray:[getDict objectForKey:@"DATA"]];
                            _targetDate = [getDict objectForKey:@"MSG_NEW_TARGET_DATE"];
                            NSArray* reversedArray = [[arr reverseObjectEnumerator] allObjects];
                            NSMutableArray *tempArr = [NSMutableArray arrayWithArray:reversedArray];
                            //                    [_arr addObjectsFromArray:tempArr];
                            NSRange arrRange = NSMakeRange(0, tempArr.count);
                            NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:arrRange];
                            [_arr insertObjects:tempArr atIndexes:set];
                            NSLog(@"%@",_arr);
                            NSMutableArray *mgroupsArray = [NSMutableArray array];
                            for (NSDictionary *chatDict in _arr) {
                                chatModel *chatResult = [chatModel chatWithDictionary:chatDict];
                                [mgroupsArray addObject:chatResult];
                            }
                            _chatResultArr = mgroupsArray;
                            
                            [self.tabV reloadData];
                        }else{
                            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Network error" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                            alert.delegate = self;
                            [alert show];
                        }
                        
                    }else{
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"No more historical data" message:nil delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil, nil];
                        alert.delegate = self;
                        [alert show];
                    }
                }else{
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Network error" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                    alert.delegate = self;
                    [alert show];
                }
               
            }];
        }else{
            NSLog(@"没有网");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"There is no network" message:nil delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil, nil];
            alert.delegate = self;
            [alert show];
        }
    }];

}

- (void)clickVoice{
    
    DemoViewController *voiceVc = [[DemoViewController alloc]init];
    voiceVc.delegate = self;
    voiceVc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    
    voiceVc.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:voiceVc animated:YES completion:nil];
    
}

- (void)send:(NSData *)data
{
    
    _dataName = [self getNameBaseCurrentTime:@".MP3"];
    [_TCPManage reciveData:data];
    [_TCPManage connect:@"voice"];
    [_TCPManage getName:_dataName];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:COMPANY forKey:@"COMPANY"];
    [dict setObject:_messageID forKey:@"MESSAGEID"];
    [dict setObject:_userID forKey:@"USERID"];
    [dict setObject:_dataName forKey:@"DATA_FILE_NAME"];
    
    NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
    
    NSString *strResult = [NSString stringWithFormat:@"AUDIO@@%@",str];
    
    NSData *dataResult = [strResult dataUsingEncoding:NSUTF8StringEncoding];
    
//    [self.clientSocket writeData:dataResult withTimeout:-1 tag:10];
    [_TCPManage writeData:dataResult];
    
}

- (void)photoClick{
    
    UIImagePickerController *pick=[[UIImagePickerController alloc]init];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pick.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        pick.allowsEditing=true;
        pick.delegate=self;
        [self presentViewController:pick animated:true completion:nil];
    }else{
        NSLog(@"相册不可用");
    }
    
}

- (void)clickVideo{
    
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        picker.videoQuality = UIImagePickerControllerQualityTypeMedium; //录像质量
        
        picker.videoMaximumDuration = 10.0f; //录像最长时间
        picker.mediaTypes = [NSArray arrayWithObjects:@"public.movie", nil];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"reminder" message:@"The current device does not support video" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:nil];
        [alert show];
    }
    //跳转到拍摄页面
    [self presentViewController:picker animated:YES completion:nil];

}
- (void)clickCamera{
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *pick=[[UIImagePickerController alloc]init];
        pick.sourceType=UIImagePickerControllerSourceTypeCamera;//设置 pick 的类型为相机
        pick.allowsEditing=true;//设置是否可以编辑相片涂鸦
        pick.delegate=self;
        [self presentViewController:pick animated:true completion:nil];
    }
    else
    {
        NSLog(@"相机不可用");
    }
    NSLog(@"拍摄照片");
}


//改变界面位置
- (void)viewChanged:(NSNotification *)userInfo
{
    NSDictionary * dict = userInfo.userInfo;
    CGRect keyboardF = [dict[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat ty = keyboardF.origin.y-[UIScreen mainScreen].bounds.size.height;
    NSTimeInterval time = [dict[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    [UIView animateWithDuration:time animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0, ty);
    }];
}

//改变界面位置
- (void)viewChanged
{
    [self.view endEditing:YES];
    [UIView animateWithDuration:0.5 animations:^{
        
        CGRect tempViewF = self.backView.frame;
        tempViewF.origin.y = -100;
        self.backView.frame = tempViewF;
        
    }];
}

//tableView开始滚动退出编辑状态
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [UIView animateWithDuration:0.2 animations:^{
        CGRect tempViewF = self.backView.frame;
        tempViewF.origin.y = 0;
        self.backView.frame = tempViewF;
        
    }];
    [self.view endEditing:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type=[info objectForKey:UIImagePickerControllerMediaType];
    
    //判断选择的是否是图片,这个 public.image和public.movie是固定的字段.
    if ([type isEqualToString:@"public.image"])
    {
        UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
        _dataName = [self getNameBaseCurrentTime:@".png"];  
        [_TCPManage getName:_dataName];
        if (picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
            UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
        }
        
        NSData *imageData = [UIImage compressWithOrgImg:image];

        [_TCPManage reciveData:imageData];
        NSString *base64String = [imageData base64EncodedStringWithOptions:0];
        _dataString = base64String;
        
        [_TCPManage connect:@"photo"];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:COMPANY forKey:@"COMPANY"];
        [dict setObject:_messageID forKey:@"MESSAGEID"];
        [dict setObject:_userID forKey:@"USERID"];
        [dict setObject:_dataName forKey:@"DATA_FILE_NAME"];
        
        NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
        
        NSString *strResult = [NSString stringWithFormat:@"IMAGE@@%@",str];
        NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
        
        [_TCPManage writeData:data];
        
        NSLog(@"图片");
        //判断选择的是否是视频
    }else if ([type isEqualToString:@"public.movie"]) {
        _dataName = [self getNameBaseCurrentTime:@".mov"];
        [_TCPManage getName:_dataName];
        _dataType = @"movie";
        NSURL *sourceURL = info[UIImagePickerControllerMediaURL];
        
        NSData *movdata = [NSData dataWithContentsOfURL:sourceURL];
        [_TCPManage reciveData:movdata];
        [self.clientSocket connectToHost:[NSUD objectForKey:@"URL"] onPort:9997 viaInterface:nil withTimeout:-1 error:nil];
        [_TCPManage connect:@"movie"];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:@"000" forKey:@"COMPANY"];
        [dict setObject:_messageID forKey:@"MESSAGEID"];
        [dict setObject:_userID forKey:@"USERID"];
        [dict setObject:_dataName forKey:@"DATA_FILE_NAME"];
        
        NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
        
        NSString *strResult = [NSString stringWithFormat:@"VIDEO@@%@",str];
        NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
        
        [_TCPManage writeData:data];
    }
    [picker dismissViewControllerAnimated:false completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"取消");
    [picker dismissViewControllerAnimated:false completion:nil];
}

#pragma mark ————————— 以当前时间合成视频名称 —————————————
- (NSString *)getNameBaseCurrentTime:(NSString *)type{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    int value = (arc4random() % 10000) + 1;
    NSString *str = [NSString stringWithFormat:@"%@%d",[dateFormatter stringFromDate:[NSDate date]],value];
    NSString *resultStr = [str stringByAppendingString:type];
    return resultStr;
}

- (void)sendMessage{
    if (_textField.text.length != 0) {
        [_TCPManage reciveText:_textField.text];
        [_TCPManage connect:@"string"];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:COMPANY forKey:@"COMPANY"];
        [dict setObject:_messageID forKey:@"MESSAGEID"];
        [dict setObject:_userID forKey:@"USERID"];
        
        NSString *length = [NSString stringWithFormat:@"%d",[self lengthWith:_textField.text]];
        
        [dict setObject:length forKey:@"DATA_LENGTH"];
        NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
        
        NSString *strResult = [NSString stringWithFormat:@"TEXT@@%@",str];
        NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
        
        [_TCPManage writeData:data];
    }
    self.textField.text = nil;
    [self.textField endEditing:YES];
}

- (int)lengthWith:(NSString *)str {
    int count = 0;
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if ( a > 19 && a < 127)
        {
            count ++;
        }else{
            count += 3;
        }
    }
    return count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    chatModel *chatModel = _chatResultArr[indexPath.row];
    
    chatViewCell *cell;
    
    NSString *cellIdentifier;
    
    [cell.photo setImage:[UIImage imageNamed:@""]];
    
    if ([chatModel.MSG_DATA_TYPE isEqualToString:@"TEXT"]) {
        cellIdentifier = NSStringFromClass([chatViewCell class]);
    }else if ([chatModel.MSG_DATA_TYPE isEqualToString:@"IMAGE"]){
        cellIdentifier = NSStringFromClass([chatViewImgCell class]);
    }else if ([chatModel.MSG_DATA_TYPE isEqualToString:@"VIDEO"]){
        cellIdentifier = NSStringFromClass([chatViewVideoCell class]);
    }else if ([chatModel.MSG_DATA_TYPE isEqualToString:@"AUDIO"]){
        cellIdentifier = NSStringFromClass([chatViewVoiceCell class]);
    }
    if (!cell) {
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    }
//    //自定义cell类
    cell.delegate = self;
    cell.userInteractionEnabled = NO;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell setUserInteractionEnabled:YES];
    cell.timeL.text = chatModel.MSG_DATE;
    cell.shopNameL.text = chatModel.MSG_SHOP_NAME;
    cell.nameL.text = chatModel.MSG_TANTO_NAME;
    
    
    
//    cell.longPressGesture =  [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(cellLongPress:)];
    
    if ([_userID isEqualToString:chatModel.MSG_USER_ID]) {
        [cell addGestureRecognizer:cell.longPressGesture];
        
        cell.imgV.image = [UIImage imageNamed:@"chatIcon"];
        [cell.shopNameL mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(cell.nameL);
            make.right.mas_equalTo(cell.nameL.mas_left).offset(-5);
            make.left.greaterThanOrEqualTo(cell.contentView).offset(15);
        }];
        
        [cell.nameL mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(cell.timeL.mas_bottom);
            make.right.mas_equalTo(cell.contentView).offset(-15);
            make.width.mas_lessThanOrEqualTo(100);
        }];
        
        [cell.imgV mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(cell.nameL.mas_bottom).offset(15);
            make.right.mas_equalTo(cell.contentView).offset(-15);
            make.size.mas_equalTo(CGSizeMake(45, 45));
            make.bottom.lessThanOrEqualTo(cell.contentView).offset(-15);
        }];
        if(chatModel.MSG_DATA_TEXT.length != 0){
            [cell.commentL mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(cell.imgV);
                make.right.mas_equalTo(cell.imgV.mas_left).offset(-10);
                make.width.mas_lessThanOrEqualTo(screenWidth - 80);
                make.bottom.lessThanOrEqualTo(cell.contentView).offset(-15);
            }];
            
            cell.commentL.backgroundColor = [UIColor colorWithRed:119/255.0 green:210/255.0 blue:58/255.0 alpha:1];
        }
        
        cell.photo.contentMode = UIViewContentModeScaleAspectFit;
        [cell.photo mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(cell.imgV);
            make.right.mas_equalTo(cell.imgV.mas_left).offset(-10);
            make.height.mas_equalTo(80);
            make.width.mas_equalTo(80);
            make.bottom.lessThanOrEqualTo(cell.contentView).offset(-15);
        }];
        
    }else{
        

        [cell removeGestureRecognizer:cell.longPressGesture];
        
        [cell.shopNameL mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(cell.timeL.mas_bottom);
            make.left.mas_equalTo(cell.contentView).offset(15);
            make.width.mas_lessThanOrEqualTo(100);
        }];
        
        [cell.nameL mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(cell.timeL.mas_bottom);
            make.left.mas_equalTo(cell.shopNameL.mas_right).offset(5);
            make.width.mas_lessThanOrEqualTo(100);
        }];
        [cell.imgV mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(cell.nameL.mas_bottom).offset(15);
            make.left.mas_equalTo(cell.contentView).offset(15);
            make.size.mas_equalTo(CGSizeMake(45, 45));
            make.bottom.lessThanOrEqualTo(cell.contentView).offset(-15);
        }];
        cell.imgV.image = [UIImage imageNamed:@"chatIcon"];
        
        if(chatModel.MSG_DATA_TEXT.length != 0){
            
            [cell.commentL mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(cell.imgV);
                make.left.mas_equalTo(cell.imgV.mas_right).offset(10);
                make.width.mas_lessThanOrEqualTo(screenWidth - 80);
                make.bottom.lessThanOrEqualTo(cell.contentView).offset(-15);
            }];
            cell.commentL.backgroundColor = [UIColor whiteColor];
            
        }
        
        cell.photo.contentMode = UIViewContentModeScaleAspectFit;
        [cell.photo mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(cell.imgV);
            make.left.mas_equalTo(cell.imgV.mas_right).offset(10);
            make.height.mas_equalTo(80);
            make.width.mas_equalTo(80);
            make.bottom.lessThanOrEqualTo(cell.contentView).offset(-15);
        }];
    }
    
    if(chatModel.MSG_DATA_IMG.length != 0){
        cell.photo.hidden = NO;
        [cell.photo sd_setImageWithURL:[NSURL URLWithString:chatModel.MSG_DATA_IMG]];
//        [_imageV sd_setImageWithURL:[NSURL URLWithString:chatModel.MSG_DATA_IMG]];
        AimTapGestureRecognizer *tapGesture = [[AimTapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        tapGesture.imgUrl = chatModel.MSG_DATA_IMG;
        [cell.photo addGestureRecognizer:tapGesture];
    }else if(chatModel.MSG_DATA_VIDEO.length != 0){
        
        cell.photo.hidden = NO;
        [cell.photo setImage:[UIImage imageNamed:@"play"]];
        cell.photo.contentMode = UIViewContentModeScaleAspectFit;
        AimTapGestureRecognizer *tapGesture = [[AimTapGestureRecognizer alloc]initWithTarget:self action:@selector(playVideo:)];
        tapGesture.videoUrl = chatModel.MSG_DATA_VIDEO;
        [cell.photo addGestureRecognizer:tapGesture];
        
    }else if (chatModel.MSG_DATA_VOICE.length != 0){
        cell.photo.hidden = NO;
        if ([_userID isEqualToString:chatModel.MSG_USER_ID]) {
            [cell.photo sd_setImageWithURL:[NSURL URLWithString:chatModel.MSG_DATA_VOICE] placeholderImage:[UIImage imageNamed:@"play_r6"]];
        }else{
            [cell.photo sd_setImageWithURL:[NSURL URLWithString:chatModel.MSG_DATA_VOICE] placeholderImage:[UIImage imageNamed:@"play_l6"]];
        }
        
        AimTapGestureRecognizer *tapGesture = [[AimTapGestureRecognizer alloc]initWithTarget:self action:@selector(playVoice:)];
        tapGesture.voiceUrl = chatModel.MSG_DATA_VOICE;
        
        NSURL *tmpUrl = [NSURL URLWithString:chatModel.MSG_DATA_VOICE];
        _voiceUrl = tmpUrl;
        [cell.photo addGestureRecognizer:tapGesture];
    }else if(chatModel.MSG_DATA_TEXT.length != 0){
        cell.commentL.text = chatModel.MSG_DATA_TEXT;
        cell.commentL.layer.cornerRadius = 5;
        cell.photo.hidden = YES;
    }else if(chatModel.MSG_DATA_IMG.length == 0){
        cell.photo.hidden = NO;
        [cell.photo setImage:[UIImage imageNamed:@"icon"]];
    }
    
    if (indexPath.row % 2 == 0) {
        
        cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:3/255.0 blue:255/255.0 alpha:0.2];
        
    } else {
        
        cell.backgroundColor = [UIColor clearColor];
    }
    return cell;
}



//配置和显示UIMenuController
- (void)cellLongPress:(UIGestureRecognizer *)recognizer{
    CGPoint tmpPointTouch = [recognizer locationInView:self.tabV];
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        NSIndexPath *indexPath = [self.tabV indexPathForRowAtPoint:tmpPointTouch];
        chatViewCell *cell = (chatViewCell *)recognizer.view;
        [self.textField resignFirstResponder];
        [cell becomeFirstResponder];
        UIMenuItem *itDelete = [[UIMenuItem alloc] initWithTitle:@"delete" action:@selector(handleDeleteCell:)];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        [menu setMenuItems:[NSArray arrayWithObjects:itDelete,nil]];
        [menu setTargetRect:cell.frame inView:self.tabV];
        [menu setMenuVisible:YES animated:YES];
        if (indexPath == nil) {
            NSLog(@"not tableView");
        }else{
            _indexPathFlag = indexPath;
        }
    }
}


- (void)handleDeleteCell:(id)sender{//删除cell
    
    chatModel *tmpModel = _chatResultArr[_indexPathFlag.row];
    NSLog(@"%@",tmpModel.MSG_COMMENT_NO);
    //网络请求
    NSString *webServiceStr = [NSString stringWithFormat:
                               @"<web:deletePostCommentData>\
                               <arg0>%@</arg0>\
                               <arg1>%@</arg1>\
                               <arg2>%@</arg2>\
                               </web:deletePostCommentData>",COMPANY,_messageID,tmpModel.MSG_COMMENT_NO];
    //初始化网络工具类
    NetWorkTools *tools = [NetWorkTools shareTools];
    //发送网络请求
    [tools request:POST urlString:[NSString stringWithFormat:@"http://%@:8888/webservice/ws/PostCommentImplPort?wsdl",[NSUD objectForKey:@"URL"]] parametersStr:webServiceStr finished:^(id responseObject, NSError *error) {
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *string = result;
        NSLog(@"%@----",result);
        NSRange startRange = [string rangeOfString:@"<return>"];
        NSRange endRange = [string rangeOfString:@"</return>"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        NSString *resultString = [string substringWithRange:range];
        NSLog(@"%@+++++",resultString);
        
        //TANTO_CD标识存入用户偏好设置
        if([resultString isEqualToString:@"SUCCESS"]){
            [self.chatResultArr removeObjectAtIndex:_indexPathFlag.row];
            [self.tabV deleteRowsAtIndexPaths:[NSArray arrayWithObject:_indexPathFlag] withRowAnimation:UITableViewRowAnimationFade];
            [self.tabV reloadData];
        }
    }];
    
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
     if (self.textField.isFirstResponder) { // 文本框弹出键盘, 文本框才是第一响应者
          return NO;
     }

     return [super canPerformAction:action withSender:sender];
 }

- (BOOL)canBecomeFirstResponder{
    return YES;
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _chatResultArr.count;
}
- (void)close{
//    [_udpSocket close];
//    [[UDPManage shareUDPManage] disconnect];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:COMPANY forKey:@"COMPANY"];
    [dict setObject:_messageID forKey:@"MESSAGEID"];
    [dict setObject:_userID forKey:@"USERID"];
    NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
    
    NSString *strResult = [NSString stringWithFormat:@"UNLOGIN@@%@",str
                           ];
    NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
    
    [_UDPManage startScanWith:data];
    _UDPManage = nil;
    _clientSocket = nil;
    [self.navigationController popViewControllerAnimated:YES];
}

//点击图片后的方法
- (void)tapAction:(AimTapGestureRecognizer *)ges{
    //创建一个黑色背景
    //初始化一个用来当做背景的View。
    
    //    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    background = bgView;
    [bgView setBackgroundColor:[UIColor blackColor]];
    [bgView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]];
    [self.view addSubview:bgView];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        //创建显示图像的视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BIG_IMG_WIDTH, BIG_IMG_HEIGHT)];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imageView = imgView;
        //要显示的图片，即要放大的图片
        [imgView sd_setImageWithURL:[NSURL URLWithString:ges.imgUrl]];
        [bgView addSubview:imgView];
        
        CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        bgView.contentSize = size;
        
        
        //设置代理scrollview的代理对象
        bgView.delegate=self;
        //设置最大伸缩比例
        bgView.maximumZoomScale=1.5;
        //设置最小伸缩比例
        bgView.minimumZoomScale=1;
        
        imgView.userInteractionEnabled = YES;
        //添加点击手势（即点击图片后退出全屏）
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
        [imgView addGestureRecognizer:tapGesture];
        
        [self shakeToShow:bgView];//放大过程中的动画
        
    } else {
        //创建显示图像的视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BIG_IMG_WIDTH , [UIScreen mainScreen].bounds.size.height)];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imageView = imgView;
        //要显示的图片，即要放大的图片
        [imgView sd_setImageWithURL:[NSURL URLWithString:ges.imgUrl]];
        [bgView addSubview:imgView];
        
        CGSize size = CGSizeMake(BIG_IMG_WIDTH - 200 , [UIScreen mainScreen].bounds.size.height - 200);
        bgView.contentSize = size;
        
        //设置代理scrollview的代理对象
        bgView.delegate=self;
        //设置最大伸缩比例
        bgView.maximumZoomScale=1.5;
        //设置最小伸缩比例
        bgView.minimumZoomScale=1;
        
        imgView.userInteractionEnabled = YES;
        //添加点击手势（即点击图片后退出全屏）
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeView)];
        [imgView addGestureRecognizer:tapGesture];
        
        [self shakeToShow:bgView];//放大过程中的动画
        
    }
    
}

//告诉scrollview要缩放的是哪个子控件
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageView;
}

-(void)closeView{
    
    [background removeFromSuperview];
    
}

- (void)playVideo:(AimTapGestureRecognizer *)ges{
    
    NSURL * videoURL = [NSURL URLWithString:ges.videoUrl];
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:&error];
    if (error) {
        NSLog(@"error = %@",[error description]);
    }
    
    _avPlayer = [[AVPlayerViewController alloc] init];
    //    _avPlayer.player = [[AVPlayer alloc] initWithURL:videoURL];
    _avPlayer.delegate = self;
    _avPlayer.videoGravity = AVLayerVideoGravityResizeAspect;
    AVAsset *asset = [AVAsset assetWithURL:videoURL];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:asset];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    _avPlayer.player = player;
    [self presentViewController:_avPlayer animated:YES completion:^{
        [_avPlayer.player play];
    }];
    
}

- (BOOL)playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart:(AVPlayerViewController *)playerViewController
{
    //表示最小化后，dismiss掉原来视图的的layer
    return YES;
}

- (void)playerViewController:(AVPlayerViewController *)playerViewController restoreUserInterfaceForPictureInPictureStopWithCompletionHandler:(void (^)(BOOL))completionHandler
{
    //恢复原来的视图 重新present
    [self presentViewController:playerViewController animated:YES completion:^{
        completionHandler(YES);
    }];
}

- (void)playVoice:(AimTapGestureRecognizer *)ges{
    
    NSURL *url = [NSURL URLWithString:ges.voiceUrl];
    NSData *data = [NSData dataWithContentsOfURL:url];
    
    
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main"bundle:nil];
    playVoiceViewController *voiceVc = [mainStoryboard instantiateViewControllerWithIdentifier:@"playVoiceViewController"];
    voiceVc.voiceData = data;
    [self presentViewController:voiceVc animated:YES completion:nil];
}

//视频第一帧
- (UIImage*)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    
    return thumbnailImage;
}

//放大过程中出现的缓慢动画
- (void) shakeToShow:(UIView*)aView{
    
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.2;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    animation.values = values;
    [aView.layer addAnimation:animation forKey:nil];
}

#pragma mark - textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //    [self sendMessage:textField.text andType:@0];
    // 2.链接服务器
    if (textField.text.length != 0) {
        [self.clientSocket connectToHost:[NSUD objectForKey:@"URL"] onPort:9997 viaInterface:nil withTimeout:-1 error:nil];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:COMPANY forKey:@"COMPANY"];
        [dict setObject:_messageID forKey:@"MESSAGEID"];
        [dict setObject:_userID forKey:@"USERID"];
        NSString *length = [NSString stringWithFormat:@"%d",[self lengthWith:_textField.text]];
        [dict setObject:length forKey:@"DATA_LENGTH"];
        
        NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
        
        NSString *strResult = [NSString stringWithFormat:@"TEXT@@%@",str];
        NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
        
//        [self.clientSocket writeData:data withTimeout:- 1 tag:10];
        [_TCPManage writeData:data];
    }
    return YES;
}


#pragma mark - GCDAsyncSocket delegate
//- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port {
////    NSLog(@"连接成功  服务器ip: %@",host);
//    [self.clientSocket readDataWithTimeout:- 1 tag:50];
//    
//}
//
//// 收到消息
//- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag {
//    NSString *text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//    
//    //    [self sendMessage:text andType:@1];
//    [self.clientSocket readDataWithTimeout:- 1 tag:50];
//    if ([text isEqualToString:@"OK"]) {
//        if ([_dataType isEqualToString:@"string"]) {
//            NSString *strResult = _textDataString;
//            NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
//            [self.clientSocket writeData:data withTimeout:- 1 tag:10];
//
//            double delayInSeconds = 0.5;
//            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                [self.tabV reloadData];
//                [_clientSocket disconnect];
//            });
//        }else if ([_dataType isEqualToString:@"photo"]){
//            [_clientSocket writeData:_data withTimeout:- 1 tag:20];
//            double delayInSeconds = 2.0;
//            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                [self.tabV reloadData];
//                [_clientSocket disconnect];
////                [_udpSocket close];
//            });
//        }else if ([_dataType isEqualToString:@"movie"]){
//            [self.clientSocket writeData:_data withTimeout:- 1 tag:30];
//            double delayInSeconds = 3.0;
//            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                [self.tabV reloadData];
//                [_clientSocket disconnect];
////                [_udpSocket close];
//            });
//        }else{
//            [self.clientSocket writeData:_data withTimeout:- 1 tag:40];
//            double delayInSeconds = 2.0;
//            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
//            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                [self.tabV reloadData];
//                [_clientSocket disconnect];
////                [_udpSocket close];
//            });
//        }
//    }
////    [_clientSocket disconnect];
////    [_udpSocket close];
//    
////    [self viewDidLoad];
//}
- (void)refresh{
    [self.tabV reloadData];
}


- (void)receiveWithDict:(NSDictionary *)Dict{
    
        chatModel *newModel = [chatModel chatWithDictionary:Dict];
        [_chatResultArr addObject:newModel];
//        _textField.text = nil;
    //解决刷新tableView reloadData时闪屏的bug
    self.tabV.hidden = YES;
    [self.tabV reloadData];
    
    if ([_chatResultArr count] > 1){
        // 动画之前先滚动到倒数第二个消息
        [self.tabV scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_chatResultArr count] - 2 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
    self.tabV.hidden = NO;
    // 添加向上顶出最后一个消息的动画
    if ([_chatResultArr count] != 0){
        [self.tabV scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_chatResultArr count] - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }else{
        [self viewDidLoad];
    }
    
    
//        [self.tabV reloadData];

}

-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{
    //udp登录socket
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    [dict setObject:COMPANY forKey:@"COMPANY"];
//    [dict setObject:_messageID forKey:@"MESSAGEID"];
//    [dict setObject:_userID forKey:@"USERID"];
//    NSString *str = [[SBJson4Writer alloc]stringWithObject:dict];
//    
//    NSString *strResult = [NSString stringWithFormat:@"LOGIN@@%@",str
//                           ];
//    NSData *data = [strResult dataUsingEncoding:NSUTF8StringEncoding];
//    
//    [_UDPManage startScanWith:data];
//    [self viewDidLoad];
    if(err){
        NSLog(@"断开连接 %@",err);
    }
    
}

@end
